from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField
from wtforms.validators import DataRequired, Length, ValidationError, EqualTo, InputRequired
from .sql_data import User
from flask_login import current_user


class FormZh(FlaskForm):
    class Meta:
        locales = ['zh']


class LoginForm(FormZh):
    username = StringField('用户名', validators=[
        DataRequired("用户名不能为空"),
        Length(4, 10, message="用户名长度必须在4-10之间")
    ])
    password = PasswordField('密码', validators=[
        DataRequired("密码不能为空"),
        Length(4, 50, message="密码长度必须在4-50之间")
    ])
    remember = BooleanField('记住我')
    submit = SubmitField('登录')


class RegisterForm(FormZh):
    username = StringField('用户名', validators=[
        DataRequired("用户名不能为空"),
        Length(4, 10, message="用户名长度必须在4-10之间")
    ])
    password = PasswordField('密码', validators=[
        DataRequired("密码不能为空"),
        Length(4, 50, message="密码长度必须在4-50之间")
    ])
    password2 = PasswordField('确认密码', validators=[
        DataRequired("密码不能为空"),
        EqualTo('password', message="两次密码不一致")
    ])
    submit = SubmitField('注册')

    @staticmethod
    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user:
            raise ValidationError("该用户名已存在")


class EditUser(FormZh):
    """
    管理用户表单验证
    """
    username = StringField('用户名', validators=[
        DataRequired("用户名不能为空"),
        Length(4, 10, message="用户名长度必须在4-10之间")
    ])
    password = PasswordField('密码', validators=[
        DataRequired("密码不能为空"),
        Length(4, 50, message="密码长度必须在4-50之间")
    ])
    authority = SelectField('权限', choices=[('1', '普通用户'), ('2', '管理员')], validators=[
        InputRequired("权限不能为空")
    ])


class EditUserInfo(FormZh):
    """
    个人信息表单验证
    """
    username = StringField('用户名')
    password = PasswordField('新密码', validators=[
        DataRequired("新密码不能为空"),
        Length(4, 50, message="新密码长度必须在4-50之间")
    ])
    password_old = PasswordField('旧密码', validators=[
        DataRequired("旧密码不能为空"),
        Length(4, 50, message="旧密码长度必须在4-50之间")
    ])

    @staticmethod
    def validate_user_id(self, user_id):
        if current_user.id:
            user = User.query.filter_by(id=current_user.id).first()
            if not user:
                raise ValidationError("该用户不存在")
        else:
            raise ValidationError("您没有权限修改该用户信息")
